<template>
  <div>
    <div class="gva-search-box">
      <!-- 搜索框内容 -->
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog">
          新增
        </el-button>
      </div>
      <el-table
          :data="tableData"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            align="left"
            label="服务名称"
            min-width="150"
            prop="ServiceItemName"
            sortable="custom"
        />

        <el-table-column
            align="left"
            label="创建时间"
            min-width="200"
            prop="CreatedAt"
            sortable
        >
          <template #default="scope">
            {{ formatDate(scope.row.CreatedAt) }}
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" width="200">
          <template #default="scope">
<!--            <el-button type="primary" link @click="opendrawerVisible(scope.row)">-->
<!--              编辑-->
<!--            </el-button>-->
            <el-button type="primary" link @click="deleteApiFunc(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-drawer
        v-model="drawerVisible"
        title="新增节点"
        direction="rtl"
        :size="drawerSize"
        @close="resetForm"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="服务ID" prop="serviceID">
          <el-input v-model="form.serviceID" placeholder="请输入服务ID" />
        </el-form-item>
        <el-form-item label="服务名称" prop="serviceItemName">
          <el-input v-model="form.serviceItemName" placeholder="请输入服务名称" />
        </el-form-item>


        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import {
  getCapabilityList,
  addCapability,
  deleteCapability,
} from "@/api/service";

const route = useRoute();
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const serviceID = ref('');
const serviceData = ref([]);
const drawerVisible = ref(false);
const drawerSize = ref("40%");
const formRef = ref(null);
const form = ref({
  serviceID: "",
  serviceItemName: "",
  CapabilityConfig: "",
  StartTime: "",
});
const rules = {
  serviceID: [{ required: true, message: "请输入服务ID", trigger: "blur" }],
  serviceItemName: [{ required: true, message: "请输入服务名称", trigger: "blur" }],
  CapabilityConfig: [{ required: true, message: "请输入服务配置", trigger: "blur" }],
  StartTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
};

const opendrawerVisible = (row) => {
  form.value = {
    serviceID: row.serviceID,
    serviceItemName: row.serviceItemName,
    CapabilityConfig: row.CapabilityConfig,
    StartTime: new Date(row.StartTime), // Convert to Date object for date-picker
  };
  drawerVisible.value = true;
};



const getTableData = async () => {
  try {
    const ServiceId = route.query.ServiceId || '';
    const response = await getCapabilityList(page.value, pageSize.value, ServiceId);
    if (response.code === 0) {
      tableData.value = response.data.list.map((item) => ({
        ...item,
        StartTime: new Date(item.StartTime), // Convert to Date object for table display
      }));
      total.value = response.data.total;
    } else {
      ElMessage.error(response.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("获取数据失败");
  }
};

onMounted(() => {
  getTableData();
});

const openDialog = () => {
  form.value = {
    serviceID: "",
    serviceItemName: "",

  };
  drawerVisible.value = true;
  getTableData();
};

const resetForm = () => {
  formRef.value.resetFields();
};

const formatDate = (date) => {
  if (date) {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    const hours = String(d.getHours()).padStart(2, "0");
    const minutes = String(d.getMinutes()).padStart(2, "0");
    const seconds = String(d.getSeconds()).padStart(2, "0");
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  return "";
};

const parseCapabilityConfig = (config) => {
  try {
    const parsed = JSON.parse(config);
    return Object.entries(parsed)
        .map(([key, value]) => `${key}: ${value}`)
        .join(", ");
  } catch (e) {
    return config;
  }
};

const submitForm = async () => {
  try {
    await formRef.value.validate();
    const payload = {
      serviceID: form.value.serviceID,
      serviceItemName: form.value.serviceItemName,

    };
    await addCapability(payload);
    ElMessage.success("添加成功");
    drawerVisible.value = false;
    getTableData();
  } catch (error) {
    console.error("Form Submit Error:", error);
    ElMessage.error("添加失败");
  }
};

const deleteApiFunc = (row) => {
  ElMessageBox.confirm("确认删除此配置？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteCapability({ serviceItemId: row.ServiceItemId });
      ElMessage.success("删除成功");
      getTableData();
    } catch (error) {
      console.error("Delete Error:", error);
      ElMessage.error("删除失败");
    }
  });
};

const handleCurrentChange = (newPage) => {
  page.value = newPage;
  getTableData();
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  getTableData();
};

const sortChange = (sort) => {
  console.log("Sort Change:", sort);
};

const handleSelectionChange = (selection) => {
  console.log("Selection Change:", selection);
};
</script>
